package com.gitee.form_token.service;

import com.gitee.form_token.mapper.SysAccountMapper;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;

@Service("userDetailsPasswordService")
public class MyUserDetailsPasswordService implements UserDetailsPasswordService {

    @Resource
    private SysAccountMapper userMapper;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails updatePassword(UserDetails user, String oldPassword) throws UsernameNotFoundException {

        String username = user.getUsername();
        String password = user.getPassword();
        String newPassword = "{bcrypt}" + passwordEncoder.encode(oldPassword);

        if (password.startsWith("{noop}")) {
            int num = userMapper.upgradePassword(username, newPassword);
            if (num < 1) throw new BadCredentialsException("密码更新失败");
        }

        return User.builder()
                .username(username)
                .password(newPassword)
                .authorities(new ArrayList<GrantedAuthority>())
                .build();
    }
}

